package com.quanyan.stadium.service.gameRules.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.GameGroup;
import com.quanyan.stadium.mapper.TbGameEventMapper;
import com.quanyan.stadium.mapper.TbGameScheduleAddendumMapper;
import com.quanyan.stadium.mapper.VStadiumUserDefinedMapper;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.gameRules.AbsGameSystem;
import com.quanyan.stadium.service.gameRules.entity.GameRuleGenerate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoxiao
 * @date 16/4/11-14:42
 *
 *
 * 对抗赛编排
 *
 */

@Service("gameRulePkServiceImpl")
public class GameRulePkServiceImpl extends AbsGameSystem {

    private final static Logger logger = LoggerFactory.getLogger(GameRulePkServiceImpl.class);


    @Autowired
    private GameCategoryServiceImpl gameCategoryService;

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private TbGameScheduleAddendumMapper tbGameScheduleAddendumMapper;

    @Autowired
    private OfficialGameCache officialGameCache;

    @Autowired
    private TbGameEventMapper tbGameEventMapper;

    @Autowired
    private VStadiumUserDefinedMapper vStadiumUserDefinedMapper;


    /**
     * 对抗赛产生时,存在一个虚拟的队伍id(对手)
     * */
    public final static int tempTeamId = -1;


    /***
     * 创建轮次
     *
     *
     * */
    @Override
    public List<Integer> createGameRound(Integer gameEventId, Integer currentTeamNum, Map<String, Object> params) throws Exception {
        TbGameEvent tbGameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        currentTeamNum = gameCategoryService.getTeamNum(tbGameEvent, currentTeamNum);
        List<Integer> result = new ArrayList<>();
        TbGameRound gameRound = new TbGameRound();
        gameRound.setName("对抗赛");
        gameRound.setCurrentTeamNum(currentTeamNum);
        gameRound.setRankTeamNum(currentTeamNum/2);
        gameRound.setGameEventId(tbGameEvent.getId());
        gameRound.setPlaceId(tbGameEvent.getPlaceId());
        if (null == bizGameSystemDao.insertTbGameRound(gameRound).getId()) {
            throw new Exception("数据库异常");
        }
        result.add(gameRound.getId());
        return result;
    }

    @Override
    public List<Integer> createGameSchedule(TbGameEvent tbGameEvent, GameRuleGenerate gameRuleGenerate) {
        List<Integer> teamIds = this.getGameTeamList(tbGameEvent, gameRuleGenerate);
        GameGroup gameGroup = new GameGroup();
        gameGroup.setTeamHomeId(teamIds.get(0));
        gameGroup.setTeamAwayId(-1);
        gameGroup.setGameRoundId(gameRuleGenerate.getGameRoundId());
        gameGroup.setGroup(1);
        List<GameGroup> rs = new ArrayList<>();
        rs.add(gameGroup);
        return this.initSchedule(rs, gameRuleGenerate);
    }


    /**
     * 小球类个人对抗赛报名逻辑
     *
     * */
    public void updateGameSchedule(int gameEventId, List<Integer> teamIds) throws Exception {
        List<TbGameRound> roundList = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
        if (null == roundList || roundList.size() != 1) {
            throw new Exception("个人对抗赛对战表异常");
        }
        List<TbGameSchedule> gameScheduleList = bizGameSystemDao.selectTbGameScheduleByGameRoundId(roundList.get(0).getId(),0, 10);
        if (null == gameScheduleList || gameScheduleList.size() != 1) {
            throw new Exception("个人对抗赛对战表异常");
        }
        for (Integer temp : teamIds) {
            vStadiumUserDefinedMapper.updateFirstGameEventTeam(gameScheduleList.get(0).getId(), temp);
            logger.info("个人对抗赛对手更新成功");
        }

        // 更新缓存
        officialGameCache.delGameSchedule(gameScheduleList.get(0).getId());
    }

    /**
     *  对战表记录插入
     *
     **/
    public List<Integer> initSchedule(List<GameGroup> gameGroups, GameRuleGenerate gameRuleGenerate){
        List<Integer> result = new ArrayList<>();
        if (null == gameGroups) {
            return result;
        }
        for (GameGroup group : gameGroups) {
            TbGameSchedule schedule = new TbGameSchedule();
            schedule.setGameRoundId(group.getGameRoundId());
            schedule.setGroupType(group.getGroup().byteValue());
            if (group.getIsWin() || (null!=group.getTeamAwayId() && group.getTeamAwayId().intValue() == 0)) { //校验出现轮空的情况
                schedule.setIsWin(GameConstants.IS_DELETE);
                schedule.setStatus(GameConstants.RECORD_SUCCESS);
                schedule.setIsEnd(GameConstants.IS_DELETE);
                schedule.setFinalScore("1:0");
            }
            TbGameSchedule scheduleTemp = bizGameSystemDao.insertTbGameSchedule(schedule); //插入记录 对战记录
            result.add(scheduleTemp.getId());
            if (gameRuleGenerate.getIsDouble()) {
                List<TbTeamDoubleAddendum> temp = gameRuleGenerate.getTbTeamDoubleAddendumList();
                Map<Integer, TbTeamDoubleAddendum> addendumMap = new HashMap<>();
                for (TbTeamDoubleAddendum tbTeamDoubleAddendum : temp) {
                    addendumMap.put(tbTeamDoubleAddendum.getId(), tbTeamDoubleAddendum);
                }

                Gson gson = new Gson();
                List<Integer> gameEventHomeTeamIds = gson.fromJson(addendumMap.get(group.getTeamHomeId()).getTeamIdGson() ,new TypeToken<List<Integer>>() {
                }.getType());
                for (Integer tempInt :gameEventHomeTeamIds) {
                    TbGameScheduleAddendum addendum1 = new TbGameScheduleAddendum();
                    addendum1.setGameScheduleId(scheduleTemp.getId());
                    addendum1.setType((byte) 0);
                    addendum1.setEventTeamId(tempInt);
                    tbGameScheduleAddendumMapper.insertSelective(addendum1);
                }

                List<Integer> gameEventAwayTeamIds = new ArrayList<>();
                if (group.getTeamAwayId() != 0) {   //轮空逻辑处理
                    if (group.getTeamAwayId().intValue() == GameRulePkServiceImpl.tempTeamId ) {
                        gameEventAwayTeamIds.add(GameRulePkServiceImpl.tempTeamId);
                        gameEventAwayTeamIds.add(GameRulePkServiceImpl.tempTeamId);
                    }else {
                        gameEventAwayTeamIds = gson.fromJson(addendumMap.get(group.getTeamAwayId()).getTeamIdGson() ,new TypeToken<List<Integer>>() {
                        }.getType());
                    }
                }
                for (Integer tempInt :gameEventAwayTeamIds) {
                    TbGameScheduleAddendum addendum2 = new TbGameScheduleAddendum();
                    addendum2.setGameScheduleId(scheduleTemp.getId());
                    addendum2.setType((byte) 1);
                    addendum2.setEventTeamId(tempInt);
                    tbGameScheduleAddendumMapper.insertSelective(addendum2);
                }

            }else {
                TbGameScheduleAddendum addendum1 = new TbGameScheduleAddendum();
                addendum1.setGameScheduleId(scheduleTemp.getId());
                addendum1.setType((byte) 0);
                addendum1.setEventTeamId(group.getTeamHomeId());
                TbGameScheduleAddendum addendum2 = new TbGameScheduleAddendum();
                addendum2.setGameScheduleId(scheduleTemp.getId());
                addendum2.setType((byte) 1);
                addendum2.setEventTeamId(group.getTeamAwayId());
                tbGameScheduleAddendumMapper.insertSelective(addendum1);
                tbGameScheduleAddendumMapper.insertSelective(addendum2);
            }
        }
        return result;
    }
}
